//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Net;
using System.Xml;
using CommunityServer.Components;
using Rss;

namespace CommunityServer.Reader.Components
{

	/// <summary>
	/// Summary description for AddFeedHelper.
	/// </summary>
	public class AddFeedHelper
	{


		#region Constructor(s)


		public AddFeedHelper()
		{

		}


		#endregion


		#region Public Methods


		public static int AddFeed(int folderId, string targetUrl)
		{
			int userId = CSContext.Current.User.UserID;
			RssFeed rssFeed = null;


			try
			{
				Feed newFeed = new Feed();

				newFeed.Url = targetUrl;
				
				rssFeed = RssFeed.Read(newFeed.CreateRequest());
			}
			catch (WebException we)
			{
                CSException csEx = new CSException(CSExceptionType.UnknownError,"Unable to add feed", we);
                csEx.Log(CSContext.Current.SettingsID);
				throw new ApplicationException("Unable to add feed. Please double check the URL specified.");
			}
			catch (XmlException)
			{
				// Thrown when the target URL is not a valid RSS feed.

				// Here, we need to head down the route of doing autodiscovery.
				try
				{
					string discoveredUrl = AutoDiscoverer.DiscoverFeedUrl(targetUrl);

					if (discoveredUrl != null)
						rssFeed = RssFeed.Read(discoveredUrl);
					
				}
				catch (InvalidOperationException)
				{
					throw new ApplicationException("Unable to add the feed. The feed specified appears to be incomplete. Please attempt to contact the site administrator.");
				}

			}


			// Sometimes no XmlException is thrown, but the RSS.NET component works fine. Let's 
			// try to do it one more time.
			if (rssFeed == null || rssFeed.Channels.Count <= 0)
			{
				string discoveredUrl = AutoDiscoverer.DiscoverFeedUrl(targetUrl);

				if (discoveredUrl != null)
					rssFeed = RssFeed.Read(discoveredUrl);
			}

			// Finally, let's do one last check and if nothing's there, we have to assume all tries failed.
			if (rssFeed == null || rssFeed.Channels.Count <= 0)
			{
				throw new ApplicationException("Unable to add the feed specified. Please double check the URL, insure it's a valid URL to an RSS feed and try again.");
			}

			// Add it to to the database.
			int newFeedId = FeedReaderDataProvider.Instance().AddFeed(userId, folderId, rssFeed.Url);

			// Force the updater to update the posts.
			Feed feed	= new Feed();
			feed.FeedId = newFeedId;
			feed.Url	= rssFeed.Url;

			FeedUpdater updater = new FeedUpdater();
            updater.ProcessFeedItems(rssFeed,feed);
			return feed.FeedId;
		}


		#endregion


	}
}
